from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import request
from flask import session

from info.constants import CLICK_RANK_MAX_NEWS
from info.models import User, News
from info.modules.news import news_blu
from flask import render_template

from info.utils.common import user_login_data
from info.utils.response_code import RET


@news_blu.route('/news_collect', methods=["POST"])
@user_login_data
def news_collect():
    """
    1．获取参数
    2.校验参数
    3.查询新闻，判断新闻是否存在
    4.添加到收藏列表
    :return:
    """
    user = g.user

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="登陆用户不存在")

    # 1．获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 2.校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3.查询新闻，判断新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查到新闻数据")


    if action == "cancel_collect":
        if news in user.collection_news:
            user.collection_news.remove(news)
    else:
        # 4.添加到收藏列表
        if news not in user.collection_news:
            user.collection_news.append(news)

    # 5.返回状态
    return jsonify(errno=RET.OK, errmsg="收藏成功")





@news_blu.route("/<int:news_id>")
@user_login_data
def news_detail(news_id):
    """

    :param news_id:
    :return:
    """
    # 显示用户是否登陆逻辑

    user = g.user


    new_list = []
    try:
        new_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 将从数据库中取出的模型对象new_list转换乘json格式(字典形式)，使用到to_basic_dict()函数
    new_dict_li = []
    for news in new_list:
        new_dict_li.append(news.to_basic_dict())

    news = None

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        abort(404)

    news.clicks += 1

    is_collected = False

    if user:
        if news in user.collection_news:
            is_collected = True


    data = {
        "user": user.to_dict() if user else None,
        "new_dict_li": new_dict_li,
        "news":news.to_dict(),
        "is_collected": is_collected,
    }

    return render_template("news/detail.html",data=data)